<template>
  <div class="material">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button class="btn search" @click="getMaterialList" v-if="intype == 1"
        ><el-icon class="icon" color="#fff"> <Search /> </el-icon
        >查询</el-button
      >
      <el-button class="btn save" @click="handleSubmit"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >确定</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <!-- 筛选条件 -->
    <div class="search" v-if="intype == 1">
      <div class="search-item">
        <el-input
          clearable
          v-model="params.materialName"
          class="search-input"
          maxlength="30"
          placeholder="请输入物料名称"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.factoryCode"
          class="search-input"
          maxlength="30"
          placeholder="请输入出厂型号"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.technologyParameter"
          class="search-input"
          maxlength="30"
          placeholder="请输入技术参数"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.supplierName"
          class="search-input"
          maxlength="30"
          placeholder="请输入供应商名称"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.manufactureName"
          class="search-input"
          maxlength="30"
          placeholder="请输入生产厂商名称"
        ></el-input>
      </div>
    </div>
    <div class="material-container">
      <!--分类数据-->
      <div class="class-container" v-if="intype == 1">
        <div class="class-top">
          <el-input
            v-model="className"
            placeholder="搜索分类"
            clearable
            class="class-input"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="classOptions"
            :props="{ label: 'categoryName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="deptTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span
                class="span-ellipsis"
                :title="node.label.length > 18 ? node.label : ''"
                >{{ node.label }}
                <el-icon
                  v-if="data.importantDevice == 1"
                  style="margin-left: 5px; transform: translateY(2px)"
                  title="贵重设备"
                  color="#FF9552"
                  :size="15"
                >
                  <Box />
                </el-icon>
              </span> </template
          ></el-tree>
        </div>
      </div>
      <div style="width: 100%">
        <!-- 表格数据 -->
        <el-table
          v-loading="loading"
          :data="materialList"
          border
          height="64vh"
          :header-cell-style="{ 'text-align': 'center' }"
          :header-cell-class-name="cellClass"
          ref="multipleTableRef"
          @select="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="物料编号"
            prop="materialCode"
            :show-overflow-tooltip="true"
            min-width="100"
          >
            <template #default="{ row }">
              <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="物料名称"
            prop="materialName"
            :show-overflow-tooltip="true"
            min-width="120"
          >
            <template #default="{ row }">
              <span class="ellipsisStyle">{{
                row.materialName ? row.materialName : "--"
              }}</span>
            </template></el-table-column
          >
          <el-table-column
            label="是否为贵重物品"
            prop="importantDevice"
            :show-overflow-tooltip="true"
            min-width="120"
          >
            <template #default="{ row }">
              <span>{{ row.importantDevice == 1 ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="intype == 1"
            label="采购名称"
            prop="purchaseName"
            :show-overflow-tooltip="true"
            min-width="100"
          >
            <template #default="{ row }">
              <span class="ellipsisStyle">{{ row.purchaseName }}</span>
            </template></el-table-column
          >
          <el-table-column
            v-if="intype == 1"
            label="销售名称"
            prop="saleName"
            :show-overflow-tooltip="true"
            min-width="100"
          >
            <template #default="{ row }">
              <span class="ellipsisStyle">{{ row.saleName }}</span>
            </template></el-table-column
          >
          <el-table-column
            label="出厂型号"
            prop="factoryCode"
            :show-overflow-tooltip="true"
            min-width="120"
          >
            <template #default="{ row }">
              <span class="ellipsisStyle">{{ row.factoryCode }}</span>
            </template></el-table-column
          >
          <el-table-column
            v-if="intype == 1"
            label="销售型号"
            prop="saleCode"
            :show-overflow-tooltip="true"
            min-width="120"
          >
            <template #default="{ row }">
              <span class="ellipsisStyle">{{ row.saleCode }}</span>
            </template></el-table-column
          >
          <el-table-column
            label="技术参数"
            prop="technologyParameter"
            :show-overflow-tooltip="true"
            min-width="120"
          />

          <el-table-column
            label="单位"
            prop="materialUnitName"
            :show-overflow-tooltip="true"
            min-width="60"
          />
          <el-table-column
            v-if="intype == 2"
            label="采购数量"
            prop="purchaseNumber"
            :show-overflow-tooltip="true"
            min-width="100"
          />
          <el-table-column
            v-if="intype == 2"
            label="采购单价(元)"
            prop="purchasePrice"
            :show-overflow-tooltip="true"
            min-width="100"
          />
          <el-table-column
            v-if="intype == 2"
            label="税率(%)"
            prop="taxRate"
            :show-overflow-tooltip="true"
            min-width="80"
          />
          <el-table-column
            v-if="intype == 2"
            label="税额(元)"
            prop="taxAmount"
            :show-overflow-tooltip="true"
            min-width="80"
          />
          <el-table-column
            v-if="intype == 2"
            label="不含税金额(元)"
            prop="noTaxAmount"
            :show-overflow-tooltip="true"
            min-width="100"
          />
          <el-table-column
            v-if="intype == 2"
            label="运费(元)"
            prop="freight"
            :show-overflow-tooltip="true"
            min-width="80"
          />
          <el-table-column
            v-if="intype == 2"
            label="采购总价(元)"
            prop="purchaseAmount"
            :show-overflow-tooltip="true"
            min-width="100"
          />
          <el-table-column
            v-if="intype == 2"
            label="发票类型"
            prop="invoiceTypeName"
            :show-overflow-tooltip="true"
            min-width="100"
          />
          <el-table-column
            v-if="intype == 2"
            label="到货周期"
            prop="deliveryCycle"
            :show-overflow-tooltip="true"
            min-width="100"
          />
          <el-table-column
            v-if="intype == 2"
            label="渠道"
            prop="channelName"
            :show-overflow-tooltip="true"
            min-width="100"
          />
          <el-table-column
            label="供应商"
            prop="supplierName"
            :show-overflow-tooltip="true"
            min-width="120"
          />
          <el-table-column
            v-if="intype == 1"
            label="生产厂商"
            prop="manufactureName"
            :show-overflow-tooltip="true"
            min-width="120"
          />
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <pagination
      class="pagination"
      :total="total"
      v-model:page="params.pageNum"
      v-model:limit="params.pageSize"
      @pagination="getMaterialList"
    />
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
import { getDictsApi } from "@/api/dict";
import { getMaterialClassListApi } from "@/api/information/materialClass";
import { getInorderMaterialList } from "@/api/stock/inorder";
const emit = defineEmits([
  // 客户新增组件显隐
  "selectionMaterialShow",
  // 更新客户新增组件显隐
  "update:selectionMaterialShow",
  // 确定选中
  "submitChoose",
]);

// 搜索参数
const params = reactive({
  categoryId: null,
  factoryCode: "",
  materialCode: "",
  materialName: "",
  stockType: null,
  supplierName: "",
  pageNum: 1,
  pageSize: 50,
  intype: 1,
  purchaseContractId: "",
});

let { intype, purchaseContractId } = toRefs(params);
// 表格加载效果
const loading = ref(false);
// 物料列表
const materialList = ref([]);
// 总数
const total = ref(0);
// 分类名称
const className = ref("");

// 存货类型列表
const stockTypeList = ref([]);
// 分类列表
const classOptions = ref(undefined);
//默认选中
const deptTreeRef = ref(null);
// 表格选中项
const multipleSelection = ref([]);
const multipleTableRef = ref(null);
/**
 * @description: 获取物料列表
 */
const getMaterialList = async (flag) => {
  if (flag) {
    params.categoryId = null;
  }
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;

    const res = await getInorderMaterialList({ pageNum, pageSize }, params);

    materialList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 获取分类列表
 */
const getMaterialClassList = async () => {
  const res = await getMaterialClassListApi();
  let obj = [
    {
      categoryId: 0,
      categoryName: "全部",
      parentId: null,
      children: [],
      id: 0,
    },
  ];
  res.rows.forEach((item) => {
    item.id = item.categoryId;
  });
  let treeData = proxy.handleTree(res.rows, "id");
  obj[0].children.push(...treeData);
  classOptions.value = obj;
  // 设置默认选中的节点的 key 值
  setTimeout(() => {
    deptTreeRef.value.setCurrentKey(0);
  }, 0);
};

const handleMaterial = async (type, purchaseContractId) => {
  params.intype = type;
  params.purchaseContractId = purchaseContractId;

  getMaterialList();
};

/**
 * @description: 通过条件过滤节点
 * @param {String} value 分类名称
 * @param {Object} data 数据源
 *
 */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.categoryName.indexOf(value) !== -1;
};

/**
 * @description: 监听分类名称
 * @param {String} val 变更后分类名称
 */
watch(className, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/**
 * @description: 节点单击事件
 * @param {Object} data 数据源
 */
function handleNodeClick(data) {
  if (!data.id) {
    params.categoryId = null;
  } else {
    params.categoryId = data.id;
  }
  getMaterialList();
}

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 返回
 */
const handleBack = () => {
  emit("update:selectionMaterialShow", false);
};

/**
 * @description: 确定选中
 */
const handleSubmit = () => {
  emit("submitChoose", multipleSelection.value);
};

/**
 * @description: 隐藏表头中的全选框
 */
const cellClass = (row) => {
  if (row.columnIndex === 0) {
    return "disabledCheck";
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 存货类型
  await getDictsApi("stock_type").then((res) => {
    if (res.code === 200) {
      stockTypeList.value = res.data;
    }
  });
}

/**
 * @description: 处理表格选中
 */
const handleSelectionChange = (list, row) => {
  if (list.length === 0) {
    multipleSelection.value = [];
    return;
  }
  /*materialList.value.forEach((ele) => {
    if (ele.id === row.id) {
      //multipleTableRef.value.toggleRowSelection(ele, true);
      //multipleSelection.value = [ele];
      multipleSelection.value.push(ele)
    }
  });*/

  multipleSelection.value = list;
};

/**
 * @description: 序号
 * @param {Number} index 索引
 */
// function indexMethod(index) {
//   const currentPage = params.pageNum;
//   const pageSize = params.pageSize;
//   const truelndex = (currentPage - 1) * pageSize + index + 1;
//   return truelndex;
// }

onMounted(() => {
  getMaterialClassList();
  getDicts();
});

defineExpose({
  handleMaterial,
});
</script>

<style lang="scss" scoped>
.material {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  .material-container {
    display: flex;

    .class-container {
      width: 240px;
      margin-right: 10px;
      padding-top: 30px;
      background: #ffffff;
      box-shadow: 0px 0px 10px 0px rgba(26, 43, 26, 0.1);
      border-radius: 2px;
      overflow: auto;
      .class-top {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
        .class-input {
          width: 180px;
        }
      }
    }
    .span-ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .pagination {
    margin: 20px auto;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
  .image-slot .el-icon {
    font-size: 30px;
  }
  /* 去掉全选按钮 */
  ::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
    display: none !important;
  }
}
</style>
